package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupMapper checkGroupMapper;
    @Override
    public void add(CheckGroup checkGroup,Integer[] checkitemIds) {
        checkGroupMapper.add(checkGroup);
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //分别获取三个参数
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        if(queryString != null && queryString.length()>0){
            queryString="%"+queryString+"%";
        }
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> page = checkGroupMapper.findPage(queryString);
        long total = page.getTotal();
        List<CheckGroup> rows = page.getResult();
        return new PageResult(total,rows);
    }

    @Override
    public List<Integer> findCheckItemIdByCheckGroupId(Integer id) {
        return checkGroupMapper.findCheckItemIdByCheckGroupId(id);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //先删除中间表t_checkgroup_checkitem所有对应的checkitem_id
        checkGroupMapper.deleteByCheckGroupId(checkGroup.getId());
        //再添加新的中间表t_checkgroup_checkitem
        this.setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);
        //修改检查组信息
        checkGroupMapper.edit(checkGroup);

    }

    @Override
    public void delete(Integer id) {
        //删除检查组前，先删除中间表t_checkgroup_checkitem里的数据
        checkGroupMapper.deleteByCheckGroupId(id);
        //再删除t_checkgroup里的数据
        checkGroupMapper.delete(id);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupMapper.findAll();
    }

    public void setCheckGroupAndCheckItem(Integer checkgroup_id,Integer[] checkitemIds ){
        if(checkitemIds != null && checkitemIds.length>0){
            for (Integer checkitemId : checkitemIds) {
                Map<String,Integer> map=new HashMap<String,Integer>();
                map.put("checkgroup_id",checkgroup_id);
                map.put("checkitem_id",checkitemId);
                checkGroupMapper.setCheckGroupAndCheckItem(map);
            }
        }
    }

}
